import AppRoute from "@/components/AppRoute";
import React from "react";
import { MenuObject } from "types";


const viteModule = import.meta.glob('../pages/**/**');

function autoload() {
    const menuLocal = JSON.parse(localStorage.getItem('menu')!);
    if (!menuLocal || !menuLocal.state || !menuLocal.state.menu || !menuLocal.state.menu.length) return [];
    const menu = menuLocal.state.menu as any;
    let routes = formatRoute(menu);
    return routes;
}

function lazyLoad(path: string) {
    const pageModule = viteModule[`../pages${path}/index.tsx`];

    // 如果没有扫描到就直接加载 404
    const Comp = pageModule === undefined ? React.lazy(viteModule[`../pages/Errors/404.tsx`] as any) : React.lazy(pageModule as any);

    return (
        <React.Suspense fallback={<div>loading...</div>}>
            <Comp></Comp>
        </React.Suspense>
    )

}

function formatRoute(menuList: MenuObject[]) {
    const formatRoutes = [] as any[];
    menuList.forEach(m => {
        let route: any = {};
        route.path = m.path;
        route.meta = m.meta;
        if (m.children && m.children.length > 0) {
            route.children = formatRoute(m.children);
        } else {
            route.element = <AppRoute>{lazyLoad(m.path)}</AppRoute>;
        }
        formatRoutes.push(route as any);
    })
    return formatRoutes;
}

export default autoload;